package com.itheima.manager;

import cn.hutool.core.collection.CollUtil;
import com.itheima.common.R;
import com.itheima.domain.*;
import com.itheima.domain.dto.OrderMoneyDto;
import com.itheima.domain.dto.OrderReceiverDto;
import com.itheima.service.OmsOrderItemService;
import com.itheima.service.OmsOrderOperateHistoryService;
import com.itheima.service.OmsOrderService;
import com.itheima.service.UmsAdminService;
import com.itheima.vo.OrderDetailsVo;
import com.itheima.exception.BusinessException;
import com.itheima.interceptor.AdminHolder;
import com.itheima.vo.PageBeanVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class OmsOrderManager {

    @DubboReference
    OmsOrderService omsOrderService;

    @DubboReference
    UmsAdminService umsAdminService;

    @DubboReference
    OmsOrderOperateHistoryService orderOperateHistoryService;

    @DubboReference
    OmsOrderItemService omsOrderItemService;

    //分页查询订单详情
    public R findByPage(String createTime, String orderSn, Integer orderType, Integer pageNum, Integer pageSize, String receiverKeyword, Integer sourceType, Integer status) {
        PageBeanVo vo= omsOrderService.findByPage(createTime,orderSn,orderType,pageNum,pageSize,receiverKeyword,sourceType,status);
        return R.success(vo);
    }

    //批量删除订单
    public Integer delete(List<Integer> ids) {
        List<Long> orderIds = ids.stream().map(id -> id.longValue()).collect(Collectors.toList());
        List<OmsOrder> orderList = omsOrderService.findByIds(orderIds);
        if (CollUtil.isEmpty(orderList)) {
            throw new BusinessException("系统异常稍后再试");
        }
        for (OmsOrder order : orderList) {
            order.setDeleteStatus(1);  //删除状态：0->未删除；1->已删除
        }
        return omsOrderService.updateOrderList(orderList);
    }

    //批量关闭订单
    public void close(Map map) {
        List<Long> orderIds = new ArrayList<>();
        String idsStr = (String) map.get("ids");
        String[] split = idsStr.split(",");
        for (String id : split) {
            orderIds.add(Long.parseLong(id));
        }
        String note = (String) map.get("note");
        UmsAdmin umsAdmin = umsAdminService.getAdminById(AdminHolder.get().getId());
        List<OmsOrder> orderList = omsOrderService.findByIds(orderIds);
        if (CollUtil.isEmpty(orderList)) {
            throw new BusinessException("系统异常稍后再试");
        }
        for (OmsOrder order : orderList) {
            order.setStatus(4);
        }
        Integer count = omsOrderService.updateOrderList(orderList);
        if (count != null) {
            List<OmsOrderOperateHistory> historyList = new ArrayList<>();
            for (OmsOrder order : orderList) {
                OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                history.setOrderId(order.getId());
                history.setCreateTime(LocalDateTime.now());
                history.setNote(note);
                history.setOrderStatus(order.getStatus());
                history.setOperateMan(umsAdmin.getNickName());
                historyList.add(history);
            }
            orderOperateHistoryService.save(historyList);
        }
    }

    //批量发货
    public void delivery(List<OmsOrderDelivery> list) {
        List<OmsOrder> orderList = new ArrayList<>();
        for (OmsOrderDelivery omsOrderDelivery : list) {
            OmsOrder order = new OmsOrder();
            BeanUtils.copyProperties(omsOrderDelivery, order);
            if (StringUtils.isNotEmpty(omsOrderDelivery.getAddress())) {
                order.setReceiverDetailAddress(omsOrderDelivery.getAddress());
            }
            order.setId(omsOrderDelivery.getOrderId().longValue());
            order.setStatus(2);
            order.setDeliveryTime(LocalDateTime.now());
            orderList.add(order);
        }
        Integer count = omsOrderService.updateOrderList(orderList);
        if (count != null) {
            UmsAdmin umsAdmin = umsAdminService.getAdminById(AdminHolder.get().getId());
            List<OmsOrderOperateHistory> historyList = new ArrayList<>();
            for (OmsOrder order : orderList) {
                OmsOrderOperateHistory history = new OmsOrderOperateHistory();
                history.setOrderId(order.getId());
                history.setCreateTime(LocalDateTime.now());
                history.setNote("完成发货");
                history.setOrderStatus(2);
                history.setOperateMan(umsAdmin.getNickName());
                historyList.add(history);
            }
            orderOperateHistoryService.save(historyList);
        }
    }

    //根据订单id获取订单详情
    public R findById(Integer id) {
        Long orderId = id.longValue();
        OmsOrder order = omsOrderService.findById(orderId);
        List<OmsOrderOperateHistory> list = orderOperateHistoryService.findOperateHistory(orderId);
        List<OmsOrderItem> orderItemList = omsOrderItemService.findOrderItem(orderId);
        if (order == null) {
            throw new BusinessException("系统异常稍后再试");
        }
        OrderDetailsVo vo = OrderDetailsVo.init(order, list, orderItemList);

        return R.success(vo);
    }

    //备注订单
    public Integer note(Map<String, String> map) {
        Long orderId = Long.parseLong(map.get("id"));
        String note = map.get("note");
        Integer orderStatus = Integer.parseInt(map.get("status"));
        UmsAdmin umsAdmin = umsAdminService.getAdminById(AdminHolder.get().getId());
        OmsOrderOperateHistory history = new OmsOrderOperateHistory();
        history.setOrderId(orderId);
        history.setNote(note);
        history.setOrderStatus(orderStatus);
        history.setCreateTime(LocalDateTime.now());
        history.setOperateMan(umsAdmin.getNickName());
        return orderOperateHistoryService.saveOne(history);
    }


    //修改订单费用信息
    public void updateOrderMoney(OrderMoneyDto orderMoneyDto) {

        Long orderId = orderMoneyDto.getOrderId().longValue();

        if (omsOrderService.findById(orderId) == null) {
            throw new BusinessException("系统异常稍后再试");
        }
        OmsOrder order = new OmsOrder();
        BeanUtils.copyProperties(orderMoneyDto, order);
        order.setId(orderId);
        order.setModifyTime(LocalDateTime.now());
        Integer count = omsOrderService.updateOrder(order);

        if (count != null) {
            //获取当前用户adminId
            UmsAdmin umsAdmin = umsAdminService.getAdminById(AdminHolder.get().getId());
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(order.getId());
            history.setCreateTime(LocalDateTime.now());
            history.setOrderStatus(0);
            history.setNote("修改订单费用信息");
            history.setOperateMan(umsAdmin.getNickName());
            orderOperateHistoryService.saveOne(history);
        }

    }

    //修改收货人信息
    public void updateReceiver(OrderReceiverDto omsReceiverInfo) {

        Long orderId = omsReceiverInfo.getOrderId().longValue();

        if (omsOrderService.findById(orderId) == null) {
            throw new BusinessException("系统异常稍后再试");
        }
        OmsOrder order = new OmsOrder();
        BeanUtils.copyProperties(omsReceiverInfo, order);
        order.setId(orderId);
        order.setModifyTime(LocalDateTime.now());
        Integer count = omsOrderService.updateOrder(order);

        if (count != null) {
            //获取当前用户adminId
            UmsAdmin umsAdmin = umsAdminService.getAdminById(AdminHolder.get().getId());
            OmsOrderOperateHistory history = new OmsOrderOperateHistory();
            history.setOrderId(order.getId());
            history.setCreateTime(LocalDateTime.now());
            history.setOrderStatus(0);
            history.setNote("修改订单费用信息");
            history.setOperateMan(umsAdmin.getNickName());
            orderOperateHistoryService.saveOne(history);
        }
    }

}
